<script setup>
    import adminApi from "@/api/admin.js";
    import {ref} from "vue";
    import {ElMessage, ElMessageBox} from "element-plus";
    import {
        Delete,
        Plus
    } from '@element-plus/icons-vue'
    //数据表格
    const list = ref([])//当前页数据
    const total = ref(0)//总条目数

    //分页信息和搜索条件
    const adminQuery = ref({
        name: '',
        phone: '',
        page: 1,
        limit: 10
    })

    //选择时间范围
    const dateTimeRange = ref([])//dateTimeRange是一个数组，两个值开始时间，结束时间，用来选择时间范围

   /* adminApi.list(adminQuery.value).then(result => {
        list.value = result.data.records//当前页数据
        total.value = result.data.total//总条目数
    })*/

    const loadData = () => {//加载数据，分页查找
        adminApi.list(adminQuery.value).then(result => {
            if(result.code == 0) {
                list.value = result.data.records//当前页数据
                total.value = result.data.total//总条目数
            }
        })
    }

    loadData()//调用

    //条件查找，拼接条件在后端mapper已经实现
    const onSearch = () => {
        adminQuery.value.page = 1
        adminQuery.value.beginUpdateTime = null//清空上一次查询留下的beginUpdateTime和endUpdateTime
        adminQuery.value.endUpdateTime = null
        if(dateTimeRange.value && dateTimeRange.value.length == 2) {
            adminQuery.value.beginUpdateTime = dateTimeRange.value[0]
            adminQuery.value.endUpdateTime = dateTimeRange.value[1]
        }
        loadData()
    }

    //重置搜索框为空
    const reset = () => {
        adminQuery.value.name = ''
        adminQuery.value.phone = ''
        dateTimeRange.value = []
    }

    //按id删除
    const deleteById = (id) => {
        ElMessageBox.confirm(
            '您确认要删除吗?',
            '警告',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
            }
        ).then(() => {
            adminApi.deleteById(id).then(result => {
                if (result.code == 0) {
                    ElMessage.success(result.msg)
                    loadData()
                } else {
                    ElMessage.error(result.msg)
                }
            })
        })
    }

    //批量删除
    //1.双向绑定将前台勾选的id存进数组
    const ids = ref([])
    const handleSelectionChange = (rows) => {
        console.log('多选',rows)
        ids.value = rows.map(row => row.id)
        console.log(ids.value)
    }
    //执行批量删除
    const deleteAll = () => {
        ElMessageBox.confirm(
            '您确认要删除吗?',
            '警告',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
            }
        ).then(() => {
            adminApi.deleteAll(ids.value).then(result => {
                if (result.code == 0) {
                    ElMessage.success(result.msg)
                    loadData()//成功后重新加载数据，分页查找
                } else {
                    ElMessage.error(result.msg)
                }
            })
        })
    }

    //添加、编辑
    const dialogFormVisible = ref(false)//点击前默认不显示
    const admin = ref({})//admin为前台输入要添加编辑的对象，ref里的参数vue动态地帮我加上去了
    //添加
    const showAddDialog = () => {
        admin.value = {}  //清空对话框上一次留下的数据，否则会由于双向绑定把上一次添加的数据回显
        dialogFormVisible.value = true//触发点击事件showAddDialog后显示
    }

    //编辑（更新）
    const showUpdateDialog = (id) => {
        dialogFormVisible.value = true//弹出对话框
        admin.value = {}  //清空对话框上一次留下的数据，否则会由于双向绑定把上一次添加的数据回显
        adminApi.selectById(id).then(result => {
            if (result.code == 0) {//result.code==0 证明查找成功
                admin.value = result.data //result.data查找结果的值（旧值）赋值给双向绑定的admin.value（新值）
            }
        })
    }

    const addOrUpdate = () => {
        if (admin.value.id) {
            adminApi.update(admin.value).then(result => {
                if (result.code == 0) { //js里有非空值就代表true
                    ElMessage.success(result.msg)
                    dialogFormVisible.value = false//更新完自动关闭对话框
                    loadData()//成功后重新加载数据，分页查找
                } else {
                    ElMessage.error(result.msg)
                }
            })
        } else {
            adminApi.add(admin.value).then(result => {
                if (result.code == 0) {
                    ElMessage.success(result.msg)
                    dialogFormVisible.value = false//添加完自动关闭对话框
                    loadData()//成功后重新加载数据，分页查找
                } else {
                    ElMessage.error(result.msg)
                }
            })
        }
    }

    //el-switch状态切换
    const handleSwitchChange = (row) => {
        console.log(row)
        //使用update,不定义新接口
        const admin = {}
        admin.id = row.id
        admin.status = row.status
        adminApi.update(admin).then(result => {
            if (result.code == 0) {
                ElMessage.success(result.msg)
            } else {
                ElMessage.error(result.msg)
            }
        })
        //定义新接口updateStatus
        /*adminApi.updateStatus(row.id,row.status).then(result => {
            if (result.code == 0) {
                ElMessage.success(result.msg)
            } else {
                ElMessage.error(result.msg)
            }
        })*/
    }

    //图片上传
    const handleAvatarSuccess = (result) => {//result是从后端接收是阿里云返回的图片url
        admin.value.avatar = result.data;
    }

    import {useTokenStore} from '@/store/token.js'
    const tokenStore = useTokenStore();
    const headers = ref({
        //携带token传递到后端
        Authorization: tokenStore.token
    });

    //分配角色
    //添加角色相关
    //三个ref()和v-model双向绑定
    const dialogRoleVisible = ref(false)
    const roleList = ref([])
    const assignedRoleIdList = ref([])
    const showAssignedRoleDialog = (row) => {
        admin.value = row;
        adminApi.selectAssignedRole(row.id).then((result) => {
            roleList.value = result.data.roleList;//将后端数据库查询来到返回值赋值给前端双向绑定的前端js参数，js参数再体现在界面上，同样，前端改了数据之后也会因为双向绑定传给后端修改数据库
            assignedRoleIdList.value = result.data.assignedRoleIdList;
            dialogRoleVisible.value = true;
        });
    }

    //分配角色，管理员id：admin.value.id，给管理员分配新的角色的id数组:assignedRoleIdList.value
    const assignRole = () => {
        const roleIds = assignedRoleIdList.value.join(',')
        adminApi.assignRole(admin.value.id,roleIds).then(result => {
            ElMessage.success(result.msg)
            dialogRoleVisible.value = false
        })
    }
</script>

<template>
    <el-card class="">
        <template #header>
            <div class="header">
                <el-button type="success" :icon="Plus" @click="showAddDialog">添加</el-button>
                <el-button type="danger" :icon="Delete" @click="deleteAll">批量删除</el-button>
            </div>
        </template>
        <el-form :inline="true">
            <el-form-item label="名字">
                <el-input v-model="adminQuery.name" placeholder="请输入名字" clearable style="width: 200px"/>
            </el-form-item>
            <el-form-item label="手机号">
                <el-input v-model="adminQuery.phone" placeholder="请输入手机号" clearable style="width: 200px"/>
            </el-form-item>
            <!--adminQuery里没有beginUpdateTime这两个属性，后端java代码AdminQuery对象里一定要加上，但是vue很智能会自动加上，所以前端代码ref里不用写也可以-->
            <el-form-item label="更新时间" :label-width="100">
                <!--<el-date-picker
                    v-model="adminQuery.beginUpdateTime"
                    type="datetime"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    placeholder="开始时间"
                />
                <el-date-picker
                    v-model="adminQuery.endUpdateTime"
                    type="datetime"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    placeholder="结束时间"
                />-->
                <el-date-picker
                    clearable
                    v-model="dateTimeRange"
                    type="datetimerange"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    value-format="YYYY-MM-DD HH:mm:ss"
                />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="onSearch">搜索</el-button>
                <el-button type="warning" @click="reset">重置</el-button>
            </el-form-item>
        </el-form>
        <el-table :data="list" style="width: 100%" ref="multipleTableRef" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column fixed prop="id" label="ID"/>
            <el-table-column prop="name" label="名字"/>
            <el-table-column prop="password" label="密码"/>
            <el-table-column prop="phone" label="电话"/>
            <el-table-column prop="email" label="邮箱"/>
            <el-table-column prop="status" label="是否禁用">
                <template #default="scope">
                    <el-switch
                        v-model="scope.row.status"
                        style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                        :active-value="1"
                        :inactive-value="0"
                        active-text="正常"
                        inactive-text="禁用"
                        inline-prompt
                        @change="handleSwitchChange(scope.row)"
                    />
                </template>
            </el-table-column>
            <el-table-column prop="avatar" label="头像">
                <template #default="scope">
                    <img :src="scope.row.avatar" style="max-height: 40px; max-width: 120px;"/>
                </template>
            </el-table-column>
            <!-- <el-table-column prop="avatar" label="头像"/> -->
            <el-table-column prop="updateTime" label="更新时间" width="180px"/>
            <el-table-column align="center" width="200px" fixed="right" label="操作">
                <template #default="{ row }"><!--解构赋值-->
                    <el-button size="small" type="primary" @click="showUpdateDialog(row.id)">编辑</el-button>
                    <el-button size="small" type="danger" @click="deleteById(row.id)">删除</el-button>
                    <el-button size="small" type="success" @click="showAssignedRoleDialog(row)">角色</el-button>

                </template>
            </el-table-column>
        </el-table>
        <!--底部分页-->
        <el-pagination
            v-model:current-page="adminQuery.page"
            v-model:page-size="adminQuery.limit"
            :page-sizes="[10, 20, 30, 40]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @change="loadData"
            style="margin-top: 20px; justify-content: flex-end"
        />
    </el-card>


    <!--添加、编辑弹出框-->
    <el-dialog v-model="dialogFormVisible" :title="title" width="500" :lock-scroll="false">
        <el-form :model="admin">
            <el-form-item label="名字" :label-width="60">
                <el-input v-model="admin.name" autocomplete="off" />
            </el-form-item>
            <el-form-item label="密码" :label-width="60">
                <el-input v-model="admin.password" autocomplete="off" />
            </el-form-item>
            <el-form-item label="邮箱" :label-width="60">
                <el-input v-model="admin.email" autocomplete="off" />
            </el-form-item>
            <el-form-item label="手机号" :label-width="60">
                <el-input v-model="admin.phone" autocomplete="off" />
            </el-form-item>
            <el-form-item label="照片" :label-width="60">
                <el-upload
                    class="avatar-uploader"
                    action="/api/upload"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :headers="headers"
                >
                    <img v-if="admin.avatar" :src="admin.avatar" class="avatar"/>
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus/>
                    </el-icon>
                </el-upload>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取消</el-button>
                <el-button type="primary" @click="addOrUpdate">
                    确认
                </el-button>
            </div>
        </template>
    </el-dialog>

    <!-- 角色分配dialog-->
    <el-dialog title="分配角色" v-model="dialogRoleVisible" width="40%">
        <el-form ref="form" :model="admin" label-width="80px">
            <el-form-item label="用户名">
                <el-input v-model="admin.name" disabled></el-input>
            </el-form-item>
            <el-form-item label="角色列表">
                <el-checkbox-group v-model="assignedRoleIdList">
                    <el-checkbox v-for="role in roleList" :key="role.id" :label="role.id">{{role.name}}</el-checkbox>
                </el-checkbox-group>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="assignRole">保存</el-button>
                <el-button  @click="dialogRoleVisible = false">取消</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
</template>

<style scoped>
    .avatar-uploader .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }
</style>

<style>
    .avatar-uploader .el-upload {
        border: 1px dashed var(--el-border-color);
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: var(--el-transition-duration-fast);
    }

    .avatar-uploader .el-upload:hover {
        border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        text-align: center;
    }
</style>